﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Data.SqlClient;
using System.Threading;

namespace Googler
{
    public partial class ConfigurationForm : Form
    {
        public ConfigurationForm()
        {
            InitializeComponent();

        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            btnOk.Enabled = false;
            try
            {
                //Program.ConfigurationFile.AppSettings.SetValue("keywords", txtKeywords.Text);
                //Program.ConfigurationFile.ConnectionStrings.SetValue("ConnectionString", BuildConnectionString());
                Program.ConfigurationFile.AppSettings.SetValue("IsFirstRun", false.ToString());
                Program.ConfigurationFile.Save();
                CreateEmptyDatabase();
                Thread.Sleep(10000);
                ExecuteSqlFile();
                MessageBox.Show("تم التنفيذ بنجاح ، يرجى إعادة تشغيل الجهاز");
            }
            catch (Exception ex)
            {
                Program.ConfigurationFile.AppSettings.SetValue("IsFirstRun", true.ToString());
                MessageBox.Show(ex.Message);
                btnOk.Enabled = true;
            }
            finally {
            } 
        }

        private void CreateEmptyDatabase()
        {
            SqlConnection connTest = new SqlConnection(BuildConnectionString());
            bool exist = false;
            try
            {
                connTest.Open();
                exist = true;
            }
            catch
            {
                exist = false;
            }
            finally
            {
                if(connTest.State != ConnectionState.Closed)
                connTest.Close();
            }
            if (exist) 
                return;
            string createDatabase = "create database NewsCollector";
            SqlConnection conn = new SqlConnection(BuildConnectionString("master"));
            try
            {
                var command = conn.CreateCommand();
                command.CommandText = createDatabase;
                conn.Open();
                command.ExecuteNonQuery();

            }
            finally
            {

                if (conn.State != ConnectionState.Closed)
                    conn.Close();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        string BuildConnectionString()
        {
            return BuildConnectionString(txtDatabaseName.Text);
        }
        string BuildConnectionString(string databaseName)
        {
            var builder = new SqlConnectionStringBuilder();
            builder.DataSource = txtDatabaseServer.Text;
            builder.InitialCatalog = databaseName;
            //builder.UserID = txtUserID.Text;
            //builder.Password = txtPassword.Text;
            builder.IntegratedSecurity = true;//cbUseIntegratedSecurity.Checked;
            return builder.ToString();
        }
        void ExecuteSqlFile()
        {
            string sqlConnectionString = BuildConnectionString();
            FileInfo file = new FileInfo("create_database_script.sql");
            string script = file.OpenText().ReadToEnd();
            string[] satements = script.Split(new string[]{"GO"},StringSplitOptions.RemoveEmptyEntries);

            SqlConnection conn = new SqlConnection(sqlConnectionString);
            conn.Open();
            try
            {
                foreach (var s in satements)
                {
                    var command = conn.CreateCommand();
                    command.CommandText = s;
                    command.ExecuteNonQuery();
                    txtExecuted.AppendText(s+Environment.NewLine);
                }
            }
            finally
            {
                conn.Close();
            }
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            var conn = new SqlConnection(BuildConnectionString());
            try
            {
                CreateEmptyDatabase();
                conn.Open();
                conn.Close();
                MessageBox.Show("Connected Successfully"); 
            }
            catch (Exception ex)
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();

                MessageBox.Show(ex.Message);
            }
        }

        private void cbUseIntegratedSecurity_CheckedChanged(object sender, EventArgs e)
        {
            txtPassword.Enabled = txtUserID.Enabled = !cbUseIntegratedSecurity.Checked;
        }
    }
}
